<?php

namespace app\common\controller\zhongzhuan;

use app\admin\library\Auth;
use think\Config;
use think\Controller;
use think\Db;
use baiying\lib\BYTokenClient;

/**
 * 后台控制器基类
 */
class Autophonetongbu extends Controller{


    
    
    /**
     * 
     * @param type $request_data
     * $list = [
            array(
                "followUserId" => ,
                "mobile" => 18300000015,
                "name" => "测试数据15",
                "fields"=>[
                    '82705932'=>'C级(明确拒绝)',
                    '82720068'=>'https://byrobot-prod.oss-cn-hangzhou.aliyuncs.com/20240807/20240807NbT05l8528034362_19553058820.mp3'
                ]
            )
        ];
     */
    public static function startTongbu($request_data){
        
        $where = empty($request_data['where']) ? '1=1' : $request_data['where'];
        $access_token = $request_data['access_token'];
        $companyId = $request_data['companyId'];
        
        $request_starttime = empty($request_data['starttime']) ? '0' : $request_data['starttime'];

        $resultQueryList = empty($request_data['resultQueryList']) ? '' : $request_data['resultQueryList'];
        
        $query =  db('ec_ai_task')->order('id desc')->where($where);
        if(empty($request_starttime)){
            $query = $query->where('status','in',[0,1]);
        }
        
        $callJoblist = $query->select();
         
        if(empty($callJoblist)) {
            echo date("Y-m-d H:i:s") ."\r\n";
            return ;
        }
            
        foreach ($callJoblist as $key => $value){

            db('ec_ai_task')->where('id',$value['id'])->setField('status',1);

            $currentPage = 1;
            $successCount = 0;
            $apiTotal = 0;
            $msg = '未知';

            $repeat_count = 0;
            $current_job_end = false; //当前任务是否结束
            $exist_info = db('ec_ai_task_phone_request')->where('callJobId',$value['callJobId'])->find();
            $prev_request_end_time = 0;
            if(empty($exist_info)){
                $uuid = md5(uniqid());
                $id = db('ec_ai_task_phone_request')->insertGetId(['method'=>'ai_task_phone','callJobId'=>$value['callJobId'],'total'=>$value['totalCount'],
                    'uuid'=>$uuid,'createtime'=>time(),'status'=>1
                ]);                    
            }else{
                $id = $exist_info['id'];
                if($exist_info['total'] != $value['totalCount']){
                    db('ec_ai_task_phone_request')->where('id',$id)->setField('total',$value['totalCount']);
                }
                
                $repeat_count = $exist_info['repeat_count'];
//                $currentPage = $exist_info['current_page'];
                $prev_request_end_time = $exist_info['prev_request_end_time'];
                
                $successCount = $exist_info['success_total'];
            }
            
            $startTimeStamp = empty($prev_request_end_time) ? 0 : $prev_request_end_time;
            
            

//            if($repeat_count > 3) continue;
            $time_desp = 3 * 60;  //时间间隔           
            
                
            $startTimeStamp = empty($startTimeStamp) ? 0 :($startTimeStamp);
            $endTimeStamp = time() - $time_desp;
            
            if(!empty($request_starttime)){
                $startTimeStamp = strtotime($request_starttime) - 1;
                $endTimeStamp = $startTimeStamp + 1 * 5;
            }else{
                if($endTimeStamp - $startTimeStamp < $time_desp){ 
                    //如果有多个任务，且需要交替执行，则用 break；
                    continue;
                }
            }
            


            
           



            $endTime =  date('Y-m-d H:i:s', $endTimeStamp);
            $item_param = ['endTime'=>$endTime,'pageNum'=>$currentPage,'pageSize'=>500,'callJobId'=>$value['callJobId']];                  

            if(!empty($startTimeStamp)){
               $startTime = date('Y-m-d H:i:s', $startTimeStamp);
               $item_param['startTime'] =$startTime;
            }


            if(!empty($resultQueryList)){
                $item_param['resultQueryList'] =$resultQueryList;
                $item_param['startTime'] =  date('Y-m-d', time()) . '00:00:00';
                $item_param['endTime'] =  date('Y-m-d H:i:s', time());
            }
            $response = self::getAiTaskPhoneList($item_param,$access_token,$companyId);                           
//            qqq('startTongbu1',$response);


            if($response['code'] == 200){
                self::taskPhoneInsert($response['data']['list']);
                $successCount = $successCount + count($response['data']['list']);


                for($int = $response['data']['pageNum'];$int <= $response['data']['pages'];$int++){
//                        $item_param = ['startTime'=>$startTime,'endTime'=>$endTime,'pageNum'=>$currentPage,'pageSize'=>500,'callJobId'=>$value['callJobId']];                  
                    $item_param['pageNum'] = $int + 1;
                    $item_response = self::getAiTaskPhoneList($item_param,$access_token,$companyId);
                    if($item_response['code'] == 200){
                        self::taskPhoneInsert($item_response['data']['list']);

                        $successCount = $successCount + count($item_response['data']['list']);
                    }
                }


                $status = $successCount >= $value['totalCount'] ? 2 : 1;

                $save_data = [
                    'success_total'=> $successCount,
                    'repeat_count'=>$repeat_count + 1,
                    'status'=>$status,
                    'msg'=>$msg,
                    'endtime'=>time()
                ];

                if(!empty(count($response['data']['list']))){
                    $save_data['prev_request_end_time'] = $endTimeStamp;
                }


                db('ec_ai_task_phone_request')->where('id',$id)->update($save_data);
                if($status == 2){
                    $current_job_end = true;
                    db('ec_ai_task')->where('id',$value['id'])->setField('status',2);
                }


            }         

            $startTimeStamp = $endTimeStamp;

//                if($current_job_end)                    break;

        
                

            

        }
        
    }
    
    
    
    
    public static function getAiTaskPhoneList($request_data,$access_token,$companyId) {
        
        $client = new BYTokenClient($access_token);

        $method = 'byai.openapi.calljob.calldone.list'; //要调用的api名称
        $api_version = '1.0.0'; //要调用的api版本号
        

        $my_params = ['companyId' => $companyId];
        $my_params = array_merge($my_params,$request_data);
        $my_files = [];

        $result = $client->post($method, $api_version, $my_params, $my_files);
        
        return $result;
        
    }



    
    public static function taskPhoneInsert($data){
        if(empty($data)) return false;
//        qqq('startTongbu',$data);
        $fields_list = Db::getFields('fa_' . getBaiYingDataTable());
        $fields = array_keys($fields_list);
        $paichu_fields = ['id','createtime','config','status','type'];
        $end_fields = array_diff($fields,$paichu_fields);
        
        $end_data = [];
        foreach ($data as $value){
            
            
            
            $is_exist = db(getBaiYingDataTable())->where('callInstanceId',$value['callInstanceId'])->count();
//            if(strpos($value['customerTelephone'], '74529796') || strpos($value['customerTelephone'], '24755410')){
//                var_dump($value);
//                var_dump($is_exist);exit;
//            }
            if(!empty($is_exist)) continue;
            
            
            
            
            $resultList = $value['resultList'];
            if(!empty($resultList[0]['name']) && $resultList[0]['name'] == '客户意向等级'){
                preg_match('/[a-zA-Z]/', $resultList[0]['value'], $matches);
                $value['is_yixiang'] = 1;
                $value['yixiang_txt'] = $resultList[0]['value'];
                $value['yixiang_value'] = !empty($matches[0])?$matches[0]:'';                
            }else{
                $value['is_yixiang'] = 0;
            }
            $value['origin'] = 1;
            if(empty($value['yixiang_value']))                continue;
            if(!empty($value['yixiang_value'])){
                if(!in_array($value['yixiang_value'], ['A','B','C','D'])){
                    continue;
                }
            }
            
            foreach ($end_fields as $v){
                if($v == 'duration'){
                    $middle_data[$v] = empty($value[$v]) ? 0 : $value[$v];
                }else{
                    $middle_data[$v] = empty($value[$v]) ? '' : $value[$v];
                }
                
            }
            
            $middle_data['createtime'] = time();
            $middle_data['config'] = json_encode($value,JSON_UNESCAPED_UNICODE);
            
            
            $end_data[] = $middle_data;
            
        }
        
        if(empty($end_data)) return false;
        db(getBaiYingDataTable())->insertAll($end_data);
    }
    
    
}
